# coding:utf-8

from pathlib import Path
from PyPDF2 import PdfReader, PdfWriter
from customizeWindowPyfile.ProgressBarDialog import ProgressBar


def decry_encryptionPDF(pdfPath, password, type):
    """
    PDF文件加解密操作
    :param pdfPath: PDF文件路径
    :param password: 密码
    :param type: 加密操作还是解密操作
    :return:
    """
    src_folder = Path(pdfPath)

    # 获取需操作的文件集
    file_list = []
    if type == 'encry':
        file_list = list(src_folder.glob('*.pdf'))
    if type == 'decry':
        file_list = list(src_folder.glob('*加密.pdf'))

    # 显示转换进度条
    totalTaskNum = len(file_list)
    doneTaskNum = 0
    currTaskNum = 1
    bar = ProgressBar()
    bar.setProcessOnTiTle(currTaskNum, totalTaskNum)
    bar.show()

    for pdf in file_list:
        inputfile = PdfReader(str(pdf))
        outputfile = PdfWriter()

        des_file = None
        des_folder = None
        # 加解密PDF文件
        if type == 'encry':
            # 需加密的个数
            outputfile.encrypt(password)
            pageCount = len(inputfile.pages)
            # 加密文件全部内容
            for page in range(pageCount):
                outputfile.add_page(inputfile.pages[page])
            # 加密文件的路径及名称设置
            des_name = f'{pdf.stem}_加密.pdf'
            des_folder = src_folder / '加密'
            des_file = des_folder / des_name
        if type == 'decry':
            if inputfile.is_encrypted:
                # 需解密的个数
                inputfile.decrypt(password)
                pageCount = len(inputfile.pages)
                # 解密文件全部内容
                for page in range(pageCount):
                    outputfile.add_page(inputfile.pages[page])
                # 解密文件的路径及名称设置
                des_name = f'{pdf.stem}_解密.pdf'
                des_folder = src_folder / '解密'
                des_file = des_folder / des_name

        if des_folder is not None and not des_folder.exists():
            des_folder.mkdir(parents=True)

        if des_file is not None:
            # 重写文件
            with open(des_file, 'wb') as f_out:
                outputfile.write(f_out)

        doneTaskNum = doneTaskNum + 1
        currTaskNum = currTaskNum + 1
        bar.setValue(100 * doneTaskNum / totalTaskNum, 100 * (doneTaskNum - 1) / totalTaskNum,
                     100 * totalTaskNum / totalTaskNum)


if __name__ == '__main__':
    decry_encryptionPDF('D:\Desktop\功能测试\PDF文件', '12345', 'decry')
    decry_encryptionPDF('D:\Desktop\功能测试\PDF文件', '12345', 'encry')
